from mysqldb.header import *
from .serializers import *
from CallManager.serializers import AllinpayCallmeListSerializer

# from CallManager.tasks import Pulsar_Send
from StaffManager.tasks import Production_points
from StaffManager.tasks import RecordNationalIncentiveData
from datetime import timedelta

# Create your views here.
import logging

logger = logging.getLogger(__name__)


class WeChatCallMeWaiterViewSet(viewsets.ModelViewSet):
    __title__ = "呼叫接单"
    __group__ = "微信模块"
    __info__ = {"get": "我的呼叫接单列表或接单"}
    __doc__ = """
    list:\n
    <h4>我的呼叫接单列表</h4>
    retrieve:\n
    <h4>呼叫接单</h4>
        {id} 记录ID
    """
    http_method_names = ["get"]
    authentication_classes = [
        BarJWTAuthentication,
        WeChatJWTAuthentication,
        MyJWTAuthentication,
    ]
    permission_classes = [BarPermissions | WeChatPermissions | MyPermissions]
    serializer_class = NoneSerializer
    queryset = AllinpayCallmeList.objects.all().order_by("-status", "current")

    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    filterset_class = CallmeListFilterSet
    search_fields = ["reqsn", "source"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(
            self.get_queryset()
            # .filter(
            #     pid=request.placeID,
            #     target__in=[0, request.user.id],
            #     status__lt=4,
            # )
        )
        serializer = AllinpayCallmeListSerializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        # 检测订单状态
        if not instance.status == 2:
            raise serializers.ValidationError({"status": "该订单不能接单"})
        if instance.target and not instance.target == request.user.id:
            raise serializers.ValidationError({"status": "该订单不能接单"})
        # 区员工登录场所
        PlaceID = REDIS.redis_hash_key("loginPlace", request.user.id)
        if not PlaceID:
            raise serializers.ValidationError({"LogonError": "该员工未检测到登录"})
        try:
            # 取用户在职ID
            PlaceStaff = AllinpayPlacestaffList.objects.get(
                pid=PlaceID, sid=request.user.id, status=1
            )
            # 检测员工是否在岗
            isPost = AllinpayPlacestaffPost.objects.get(id=PlaceStaff.id, status=1)
            # 取呼叫配置
            Conf = AllinpayCallmeConf.objects.get(
                id=instance.rtype, pid=PlaceID, status=1
            )
            # 取应答配置
            Cosf = AllinpayCallmePost.objects.get(
                pid=PlaceID, sid=request.user.id, cid=Conf.id, status=1
            )
            # 取场所信息
            place = AllinpayPlaceList.objects.get(id=instance.pid, status=1)
        except AllinpayPlacestaffList.DoesNotExist as err:
            raise serializers.ValidationError({"PlaceStaff": "该用户已经停职"})
        except AllinpayPlacestaffPost.DoesNotExist as err:
            raise serializers.ValidationError({"StaffPost": "该员工已离岗"})
        except AllinpayCallmeConf.DoesNotExist as err:
            raise serializers.ValidationError({"CallmeConf": "该呼叫类型已禁用"})
        except AllinpayCallmePost.DoesNotExist as err:
            raise serializers.ValidationError({"CallmePost": "该员工未被允许处理该呼叫类型"})
        except AllinpayPlaceList.DoesNotExist as err:
            raise serializers.ValidationError({"Place": "该场所状态异常"})
        except BaseException as err:
            print(err)
            raise serializers.ValidationError({"BaseError": "其他错误"})

        # 检测超时
        if (instance.antime + timedelta(seconds=Conf.timeout)) < timezone.now():
            overtime = 1
        else:
            overtime = 0

        # 保存数据
        serializer = AllinpayCallmeListSerializer(
            instance,
            data={
                "target": PlaceStaff.sid,
                "status": 3,
                "retime": timezone.now(),
                "timeout": Conf.timeout,
                "overtime": overtime,
            },
            partial=partial,
        )
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class WeChatCallMeFinishViewSet(viewsets.ModelViewSet):
    __title__ = "呼叫结单"
    __group__ = "微信模块"
    __info__ = {"put": "呼叫结单"}
    __doc__ = """
    update:\n
    <h4>呼叫结单</h4>
        {id} 记录ID
    """
    http_method_names = ["put"]
    authentication_classes = [WeChatJWTAuthentication]
    permission_classes = [WeChatPermissions]
    serializer_class = NoneSerializer
    queryset = AllinpayCallmeList.objects.all()

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        # 检测订单状态
        if not instance.status == 3:
            raise serializers.ValidationError({"status": "该订单不能结单"})
        # 检测刷单机制
        if (instance.retime + timedelta(seconds=30)) > timezone.now():
            raise serializers.ValidationError({"timeout": "该订单不能立即结单"})
        try:
            place = AllinpayPlaceList.objects.get(id=instance.pid, status=1)
            types = AllinpayCallmeConf.objects.get(id=instance.rtype)
            # rewar = AllinpayRawardList.objects.get(id=types.reward)
        except AllinpayPlaceList.DoesNotExist as err:
            raise serializers.ValidationError({"Place": "该场所状态异常"})
        except AllinpayCallmeConf.DoesNotExist as err:
            raise serializers.ValidationError({"types": "呼叫类型异常"})
        # except AllinpayRawardList.DoesNotExist as err:
        #     raise serializers.ValidationError({"reward": "奖励模块异常"})
        except BaseException as err:
            raise serializers.ValidationError({"BaseError": "其他错误"})

        # 保存数据
        serializer = AllinpayCallmeListSerializer(
            instance,
            data={
                "target": request.user.id,
                "status": 4,
                "complete": timezone.now(),
                "le0": types.le0,
            },
            partial=partial,
        )
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 结算接单奖励
        res = Production_points.apply_async(
            (
                instance.pid,
                instance.target,
                instance.reqsn,
                types.name,
                2,
                types.le0,
            )
        )
        # 结算商品激励
        if types.name == "配送服务":
            # 记录订单号
            reqsn = instance.bem
            try:
                r = FsygShopreqsnList.objects.get(reqsn=reqsn)
            except FsygShopreqsnList.DoesNotExist as err:
                logger.warn(f"[{instance.reqsn}] [{reqsn}] 查找商品订单异常")
            else:
                r.delivery = instance.id
                r.save()
            # 记录激励
            r = RecordNationalIncentiveData.apply_async((reqsn, instance.reqsn))
        if types.name == "清扫服务":
            dbs = {
                "status": 3,  # 终端状态 0维修，1上机中，2待清洁，3待机中
                "localhost": instance.source,  # 终端机号
                "group": None,
                "ipaddr": None,
                "mask": None,
                "gateway": None,
            }
            # 写入缓存数据
            key = f"{instance.pid}--{instance.source}"
            REDIS.redis_hash_set("workStatus", key, dbs)

            # 发送消息队列pulsar
            from MoniterManager.tasks import doMoniterPulsarScreen

            r = doMoniterPulsarScreen.apply_async((instance.pid, dbs))

        return Response({"rescode": 200, "resmsg": serializer.data})


# 检查视图
filter_views(globals())
